package com.koala.aideddevsystemmodule.modules.transactional.propagation.service.impl;

import com.koala.aideddevsystemmodule.modules.transactional.propagation.dao.TransactionalPropagationDao;
import com.koala.aideddevsystemmodule.modules.transactional.propagation.entity.TransactionalPropagationEntity;
import com.koala.aideddevsystemmodule.modules.transactional.propagation.service.TransactionalPropagationService;
import org.springframework.aop.framework.AopContext;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * Create by koala on 2022-08-20 21:24:33
 */
@Service("transactionalPropagationService")
public class TransactionalPropagationServiceImpl extends ServiceImpl<TransactionalPropagationDao, TransactionalPropagationEntity> implements TransactionalPropagationService {

    /**
     * @Transactional:
     *      1、如果这个注解没有，调用方法1，则saveEntity()方法不存在事务，当前存在零个事务
     *      1、如果这个注解没有，调用方法2，则saveEntity()方法不存在事务，当前存在两个事务
     *      2、如果这个注解有，则saveEntity()方法存在事务，调用方法1，则当前有且只有一个事务
     *      3、如果这个注解有，则saveEntity()方法存在事务，调用方法2，则当前存在三个事务
     */
    @Transactional
    @Override
    public void saveEntity(TransactionalPropagationEntity transactionalPropagation) {
        this.save(transactionalPropagation);

        // 调用方法1：在一个事务中
        /*this.saveEntityMethod1(transactionalPropagation);
        this.saveEntityMethod2(transactionalPropagation);*/

        // 调用方法2：独立事务
        TransactionalPropagationServiceImpl transactionalPropagationService = (TransactionalPropagationServiceImpl) AopContext.currentProxy();
        transactionalPropagationService.saveEntityMethod1(transactionalPropagation);
        transactionalPropagationService.saveEntityMethod2(transactionalPropagation);
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void saveEntityMethod1(TransactionalPropagationEntity transactionalPropagation){
        Integer id = transactionalPropagation.getId() + 1;
        transactionalPropagation.setId(id);
        this.save(transactionalPropagation);
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void saveEntityMethod2(TransactionalPropagationEntity transactionalPropagation){
        Integer id = transactionalPropagation.getId() + 2;
        transactionalPropagation.setId(id);
        this.save(transactionalPropagation);

        int i = 1 / 0;
    }

}